#include <iostream>
using namespace std;

#include <web/server.h>
using namespace yazi::web;
#include <common/Mapper.hpp>
#include <Test.hpp>
#include <utility/jwt.h>
#include <utility/redisclient.h>
#include <thread>
using namespace std::chrono::_V2;
//127.0.0.1:5001/hello:name=alice&age=12
void login(const Request &request, Response &response);
void registerUser(const Request & request, Response & response);

int main()
{
    auto server = yazi::utility::Singleton<Server>::instance();// 获取 Server 单例
    server->bind("/login", login);              // 绑定 /reply 路径到 reply 函数 
    server->bind("/register",registerUser);             
    server->start();
    return 0;
}

void login(const Request &request, Response &response)
{
    Json responseJson;
    std::cout << "login..."<<std::endl;
    if(request.post().has("error"))
    {
        response.code(405);
        responseJson["message"] = request.post("error");
        responseJson["token"] = "";
        response.data(Response::JSON, responseJson.str());
        return;
    }
    // 检查请求是否是 POST 方法
    if (!request.is_post())
    {
        response.code(405);
        responseJson["message"] = "not post method";
        responseJson["token"] = "";
        response.data(Response::JSON, responseJson.str());
        return;
    }

    // 解析 POST 请求的数据，获取用户名和密码
    std::string username = request.post("username");
    std::string password = request.post("password");
    std::cout << "username:" << username << std::endl;
    std::cout << "password:" << password << std::endl;

    // 检查用户名和密码是否为空
    if (username.empty() || password.empty())
    {
        response.code(400);
        responseJson["message"] = "missing username or password";
        responseJson["token"] = "";
        response.data(Response::JSON, responseJson.str());
        return;
    }

    // 查询数据库验证用户名和密码
    Mapper<User> userMapper;
    Example<User> example;
    auto criteria = example.createCriteria();
    criteria->andEqualTo(&User::username, username);

    // 获取数据库中的用户
    auto users = userMapper.selectByExample(example);
    if (users.empty())
    {
        response.code(401);
        responseJson["message"] = "user does not exist";
        responseJson["token"] = "";
        response.data(Response::JSON, responseJson.str());
        return;
    }

    // 假设我们只找到了一个用户
    User user = users[0];

    // 验证密码，这里只是简单对比，如果密码存储是加密的需要用相应的库来验证
    if (user.password != password)
    {
        response.code(401);
        responseJson["message"] = "Incorrect password";
        responseJson["token"] = "";
        response.data(Response::JSON, responseJson.str());
        return;
    }

    // 如果验证成功，生成 JWT Token
    JWT jwt("your-256-bit-secret"); // 替换为你的实际密钥
    std::string header = R"({"alg":"HS256","typ":"JWT"})";
    std::string payload = R"({"sub":")" + std::to_string(user.id) + R"(","name":")" + user.username + R"("})";

    std::string token = jwt.generate(header, payload,3600);

    // 返回登录成功的响应
    response.code(200);
    responseJson["message"] = "Login successful";
    responseJson["token"] = token;
    response.data(Response::JSON, responseJson.str());
}


void registerUser(const Request & request, Response & response)
{
    Json responseJson;

    // 检查请求是否是 POST 方法
    if (!request.is_post())
    {
        // 如果不是 POST 请求，返回 405 Method Not Allowed
        response.code(405);
        responseJson["message"] = "Not a POST method";
        responseJson["userId"] = "";
        response.data(Response::JSON, responseJson.str());
        return;
    }

    // 获取请求体中的各项数据
    std::string username = request.post("username");
    std::string password = request.post("password");
    std::string email = request.post("email");
    std::string phone = request.post("phone");
    int age = request.post("age");
    std::string gender = request.post("gender");
    std::string idNumber = request.post("idCard");

    // 检查必要的字段是否存在
    if (username.empty() || password.empty() || email.empty() || phone.empty() || 
        age <= 0 || gender.empty() || idNumber.empty())
    {
        // 如果有字段为空，返回 400 Bad Request
        response.code(400);
        responseJson["message"] = "Missing or invalid parameters";
        responseJson["userId"] = "";
        response.data(Response::JSON, responseJson.str());
        return;
    }

    // 检查用户名是否已经存在
    Mapper<User> userMapper;
    Example<User> example;
    auto criteria = example.createCriteria();
    criteria->andEqualTo(&User::username, username);

    auto existingUsers = userMapper.selectByExample(example);
    if (!existingUsers.empty())
    {
        // 如果用户名已存在，返回 400 Bad Request
        response.code(400);
        responseJson["message"] = "Username already exists";
        responseJson["userId"] = "";
        response.data(Response::JSON, responseJson.str());
        return;
    }

    // 创建一个新用户对象并设置数据
    User newUser;
    newUser.username = username;
    newUser.password = password; // 注意：实际使用中应对密码进行加密存储
    newUser.email = email;
    newUser.phone = phone;
    newUser.age = age;
    newUser.gender = gender;
    newUser.idNumber = idNumber;

    // 将用户信息插入到数据库中
    int userId = userMapper.insert(newUser);
    
    if (userId <= 0)
    {
        // 如果插入失败，返回 500 Internal Server Error
        response.code(500);
        responseJson["message"] = "Failed to register user";
        responseJson["userId"] = "";
        response.data(Response::JSON, responseJson.str());
        return;
    }

    // 返回注册成功的响应
    response.code(201);
    responseJson["message"] = "User registered successfully";
    responseJson["userId"] = userId;
    response.data(Response::JSON, responseJson.str());
}




